package net.sf.midollo.io.log;

import net.sf.midollo.io.IOUtils;

import java.io.IOException;
import java.io.OutputStream;

public class LogOutputStream extends OutputStream {

	protected OutputStream os;
	protected OutputStream log;

	public LogOutputStream(OutputStream os, OutputStream log) {
		if (os == null)
			os = IOUtils.NULL_OUTPUT;
		if (log == null)
			log = IOUtils.NULL_OUTPUT;
		this.os = os;
		this.log = log;
	}

	public void write(int b) throws IOException {
		this.os.write(b);
		this.log.write(b);
	}

	public void write(byte b[]) throws IOException {
		this.os.write(b);
		this.log.write(b);
	}

	public void write(byte b[], int off, int len) throws IOException {
		this.os.write(b, off, len);
		this.log.write(b, off, len);
	}

	public void flush() throws IOException {
		try {
			this.os.flush();
		} finally {
			this.log.flush();
		}
	}

	public void close() throws IOException {
		IOException error = null;
		try {
			this.os.close();
		} catch (IOException e) {
			error = e;
		}
		try {
			this.log.close();
		} catch (IOException e) {
			if (error == null)
				error = e;
		}
		if (error != null)
			throw error;
	}
}
